﻿//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Activities.Hosting;
using System.Activities.Persistence;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Wicresoft.SelfService.WFHost.Code;
using Wicresoft.SelfService.WFInterface;

namespace Wicresoft.SelfService.WFHost.Code
{


    class XmlPersistenceParticipant : PersistenceParticipant
    {
        const string propertiesNamespace = "urn:schemas-microsoft-com:System.Activities/4.0/properties";
        private Guid Id;

        public XmlPersistenceParticipant(Guid id)
        {
            Id = id;
        }

        //Add any additional necessary data to persist here
        protected override void CollectValues(out IDictionary<XName, object> readWriteValues, out IDictionary<XName, object> writeOnlyValues)
        {
            base.CollectValues(out readWriteValues, out writeOnlyValues);
        }

        //Implementations of MapValues are given all the values collected from all participantsâ€™ implementations of CollectValues
        protected override IDictionary<XName, object> MapValues(IDictionary<XName, object> readWriteValues, IDictionary<XName, object> writeOnlyValues)
        {
            XName statusXname = XName.Get("Status", propertiesNamespace);

            IDictionary<XName, object> mappedValues = base.MapValues(readWriteValues, writeOnlyValues);

            ActionResult actionResult = null;

            string status = string.Empty;
            object value = null;

            //retrieve the status of the workflow
            if (writeOnlyValues.TryGetValue(statusXname, out value))
            {
                status = (string)value;
            }

            //retrieve the ActionResult object
            foreach (KeyValuePair<System.Xml.Linq.XName, object> item in writeOnlyValues)
            {
                if (item.Value is LocationInfo)
                {
                    LocationInfo li = (LocationInfo)item.Value;
                    if (li.Value is ActionResult)
                    {
                        actionResult = (ActionResult)li.Value;
                    }
                }
            }

            IOHelper.EnsureAllResultFileExists();

            IOHelper.Save(Id, status, actionResult);

            return mappedValues;
        }

        //All of the values loaded from the InstanceData property bag are provided to implementations of PublishValues.  
        protected override void PublishValues(IDictionary<XName, object> readWriteValues)
        {
            base.PublishValues(readWriteValues);
        }
    }
}
